import CompressionPlugin from 'compression-webpack-plugin';
import path from 'path'
import TerserPlugin from 'terser-webpack-plugin';

function resolve(...args) {
  return path.resolve(__dirname, '..', ...args)
}

const config = {
  projectName: "read-two",
  date: "2022-1-10",
  designWidth: 750,
  deviceRatio: {
    640: 2.34 / 2,
    750: 1,
    828: 1.81 / 2,
  },
  sourceRoot: "src",
  outputRoot: "dist",
  plugins: [
    ['@tarojs/plugin-framework-react', { reactMode: 'concurrent' }],
    ['@tarojs/plugin-inject', {
      components: {
        Text: {
          'data-track-index': "''",
          'data-track-name': "''"
        },
        View: {
          'data-track-index': "''",
          'data-track-name': "''"
        },
        Button: {
          'data-track-index': "''",
          'data-track-name': "''",
          bindagreeprivacyauthorization: 'onAgreePrivacyAuthorization'
        },
        Image: {
          'data-track-index': "''",
          'data-track-name': "''"
        }
      },
      syncApis: ['openPrivacyContract', 'onNeedPrivacyAuthorization']
    }]
  ],
  defineConstants: {},
  alias: {
    '@': resolve('src'),
    '_api': resolve('src/api'),
    '_c': resolve('src/components'),
    '_config': resolve('src/config'),
    '_utils': resolve('src/utils'),
    '_pages': resolve('src/pages'),
    '_store': resolve('src/store'),
    '_hooks': resolve('src/hooks'),
  },
  copy: {
    patterns: [
      { from: 'sitemap.json', to: 'dist/sitemap.json' },
    ],
    options: {},
  },
  framework: 'react',
  compiler: 'webpack5',
  cache: {
    enable: false // Webpack 持久化缓存配置，建议开启。默认配置请参考：https://docs.taro.zone/docs/config-detail#cache
  },
  mini: {
    // 解决子包冲突问题
    webpackChain(chain, webpack) {
      // 这个插件解决资源冲突问题
      chain.merge({
        optimization: {
          splitChunks: {
            cacheGroups: {
              default: false
            }
          },
          minimize: true
        }
      });

      // 添加TerserPlugin作为优化器
      chain.optimization
        .minimizer('terser')
        .use(TerserPlugin, [{
          terserOptions: {
            compress: {
              pure_funcs: ['console.log', 'console.info', 'console.debug'],
              drop_console: process.env.NODE_ENV === 'production',
              drop_debugger: process.env.NODE_ENV === 'production'
            },
            output: {
              comments: false
            }
          },
          extractComments: false
        }]);

      // 使用哈希值以避免文件名冲突
      chain.plugin('provide-plugin')
        .use(webpack.ProvidePlugin, [{
          process: 'process/browser',
        }]);

      chain.plugin('compression-webpack-plugin')
        .use(require('compression-webpack-plugin'), [{
          algorithm: 'gzip',
          test: /\.(js|css|html|svg)$/,
          threshold: 4096, // 降低压缩阈值
          minRatio: 0.7, // 提高压缩比
          deleteOriginalAssets: false,
        }]);
    },
    postcss: {
      pxtransform: {
        enable: true,
        config: {
          selectorBlackList: [/van-/]
        }
      },
      url: {
        enable: true,
        config: {
          limit: 1024, // 设定转换尺寸上限
        },
      },
      cssModules: {
        enable: false, // 默认为 false，如需使用 css modules 功能，则设为 true
        config: {
          namingPattern: "module", // 转换模式，取值为 global/module
          generateScopedName: "[name]__[local]___[hash:base64:5]",
        },
      },
    },
    enableSourceMap: true,
    sourceMapType: 'source-map',
    miniCssExtractPluginOption: {
      ignoreOrder: true
    },
    optimizeMainPackage: {
      enable: true
    },
  },
  h5: {
    publicPath: "/",
    staticDirectory: "static",
    postcss: {
      autoprefixer: {
        enable: true,
        config: {},
      },
      cssModules: {
        enable: false, // 默认为 false，如需使用 css modules 功能，则设为 true
        config: {
          namingPattern: "module", // 转换模式，取值为 global/module
          generateScopedName: "[name]__[local]___[hash:base64:5]",
        },
      },
    },
  },
};

module.exports = function (merge) {
  let envConfigPath = process.env.NODE_ENV === 'development' ? './dev' : './prod'
  envConfigPath += `/${process.env.DEPLOY_ENV || 'test'}`
  return merge({}, config, require(envConfigPath))
}
